/**
 * 页面模板 - 前端
 * 
 * 使用说明：
 * 1. 复制此文件到 apps/frontend/src/pages/
 * 2. 重命名文件（例如：MyNewPage.tsx）
 * 3. 搜索并替换所有 [TODO] 标记的内容
 * 4. 根据需要添加或删除功能
 */

import { useEffect, useState } from 'react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Loader2, RefreshCw, AlertCircle } from 'lucide-react';
import { get, post, put, del } from '@/lib/apiClient';

// [TODO] 定义数据接口
interface DataItem {
  id: number;
  name: string;
  description?: string;
  // 添加更多字段...
}

// [TODO] 定义 API 响应接口
interface ApiResponse {
  success: boolean;
  data: DataItem[];
  message?: string;
}

/**
 * [TODO] 修改组件名称
 */
export default function TemplatePage() {
  // ==================== 状态管理 ====================
  const [data, setData] = useState<DataItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // ==================== 数据加载 ====================
  const loadData = async () => {
    try {
      setLoading(true);
      setError(null);

      // [TODO] 修改 API 端点
      const response = await get<ApiResponse>('/your-endpoint');
      
      if (response.success) {
        setData(response.data);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : '加载数据失败');
      console.error('Failed to load data:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, []);

  // ==================== 操作函数 ====================
  
  // [TODO] 创建数据示例
  const handleCreate = async () => {
    try {
      // [TODO] 修改 API 端点和数据
      const response = await post<{ success: boolean; data: DataItem }>(
        '/your-endpoint',
        { name: '新项目', description: '描述' }
      );
      
      if (response.success) {
        // 重新加载数据
        await loadData();
      }
    } catch (err) {
      console.error('Failed to create:', err);
      alert(err instanceof Error ? err.message : '创建失败');
    }
  };

  // [TODO] 更新数据示例
  const handleUpdate = async (id: number) => {
    try {
      // [TODO] 修改 API 端点和数据
      const response = await put<{ success: boolean; data: DataItem }>(
        `/your-endpoint/${id}`,
        { name: '更新后的名称' }
      );
      
      if (response.success) {
        await loadData();
      }
    } catch (err) {
      console.error('Failed to update:', err);
      alert(err instanceof Error ? err.message : '更新失败');
    }
  };

  // [TODO] 删除数据示例
  const handleDelete = async (id: number) => {
    if (!confirm('确定要删除吗？')) return;
    
    try {
      // [TODO] 修改 API 端点
      const response = await del<{ success: boolean }>(
        `/your-endpoint/${id}`
      );
      
      if (response.success) {
        await loadData();
      }
    } catch (err) {
      console.error('Failed to delete:', err);
      alert(err instanceof Error ? err.message : '删除失败');
    }
  };

  // ==================== 渲染逻辑 ====================

  // 加载状态
  if (loading) {
    return (
      <div className="flex items-center justify-center h-96">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    );
  }

  // 错误状态
  if (error) {
    return (
      <div className="flex flex-col items-center justify-center h-96 gap-4">
        <AlertCircle className="h-12 w-12 text-destructive" />
        <p className="text-destructive">{error}</p>
        <Button onClick={loadData}>重试</Button>
      </div>
    );
  }

  // 主内容
  return (
    <div className="space-y-6">
      {/* ========== 页面标题 ========== */}
      <div className="flex items-center justify-between">
        <div>
          {/* [TODO] 修改页面标题和描述 */}
          <h1 className="text-3xl font-bold">页面标题</h1>
          <p className="text-muted-foreground mt-2">页面描述</p>
        </div>
        
        {/* 操作按钮 */}
        <div className="flex gap-2">
          <Button onClick={loadData} variant="outline" size="sm">
            <RefreshCw className="h-4 w-4 mr-2" />
            刷新
          </Button>
          {/* [TODO] 添加更多操作按钮 */}
          <Button onClick={handleCreate} size="sm">
            新建
          </Button>
        </div>
      </div>

      {/* ========== 统计卡片（可选）========== */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">总数</p>
              <p className="text-2xl font-bold">{data.length}</p>
            </div>
            <Badge variant="secondary">统计</Badge>
          </div>
        </Card>
        
        {/* [TODO] 添加更多统计卡片 */}
      </div>

      {/* ========== 主要内容区域 ========== */}
      <Card className="p-6">
        <h2 className="text-xl font-semibold mb-4">数据列表</h2>
        
        {data.length === 0 ? (
          // 空状态
          <div className="text-center py-12 text-muted-foreground">
            <p>暂无数据</p>
            <Button onClick={handleCreate} variant="outline" className="mt-4">
              创建第一条数据
            </Button>
          </div>
        ) : (
          // 数据列表
          <div className="space-y-3">
            {data.map((item) => (
              <div
                key={item.id}
                className="flex items-center justify-between p-4 border rounded-lg hover:bg-accent transition-colors"
              >
                <div className="flex-1">
                  <h3 className="font-medium">{item.name}</h3>
                  {item.description && (
                    <p className="text-sm text-muted-foreground mt-1">
                      {item.description}
                    </p>
                  )}
                </div>
                
                {/* 操作按钮 */}
                <div className="flex gap-2">
                  <Button
                    onClick={() => handleUpdate(item.id)}
                    variant="outline"
                    size="sm"
                  >
                    编辑
                  </Button>
                  <Button
                    onClick={() => handleDelete(item.id)}
                    variant="destructive"
                    size="sm"
                  >
                    删除
                  </Button>
                </div>
              </div>
            ))}
          </div>
        )}
      </Card>

      {/* ========== 其他内容（可选）========== */}
      {/* [TODO] 根据需要添加更多卡片、表格、图表等 */}
    </div>
  );
}

